package otherSAMS.jdbc;

import java.sql.*;

//数据库连接工具类
public class DBconnection {
    private static String username = "root";
    private static String password = "@yj730721";

    //第一次加载类的时候执行静态代码块，用于获取数据库驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //定义创建数据库连接的静态方法
    public static Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/sams?characterEncoding=utf-8";
        try {
            Connection connection = (Connection) DriverManager.getConnection(url, username, password);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //定义关闭数据库连接的静态方法
    public static void closeConnection(ResultSet rs, PreparedStatement ps, java.sql.Connection connection) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Connection connection = DBconnection.getConnection();
        System.out.println(connection);
        System.out.println("连接成功");


    }
}
